package com.atguigu.gmall.common.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitTemplateConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){

        // 配置RabbitTemplate对象到Spring容器中
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory) ;

        // 设置生产者确认机制的回调函数
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(ack) {
                    log.info("消息正常发给了交换机....");
                }else {
                    log.error("消息没有正常发给了交换机....cause： {}" , cause );
                }
            }

        });

        // 设置生产者回退机制的回调函数
        rabbitTemplate.setMandatory(true);                  // 让rabbitmq把错误信息回传给生产者
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("exchange: {} , routingKey: {}" , exchange , routingKey);
            }
        });

        return rabbitTemplate ;
    }

}



